<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn, TableSlotDefault } from '@/components/Table'
import { getEmployees, delEmployeeApi, batchDelEmployee } from '@/api/table'
import { ref, reactive, unref } from 'vue'
import { ElMessageBox, ElMessage, ElButton, dayjs } from 'element-plus'
import { useTable } from '@/hooks/web/useTable'
import { useRouter } from 'vue-router'
import { Search } from '@/components/Search'
import { FormSchema } from '@/components/Form'

const router = useRouter()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await getEmployees({
      pageNo: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.data.records,
      total: res.data.total
    }
  },
  fetchDelApi: async () => {
    const res = await batchDelEmployee([...unref(ids)])
    return !!res
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState

const { getList, getElTableExpose, delList } = tableMethods

const { t } = useI18n()

const columns = reactive<TableColumn[]>([
  {
    field: 'selection',
    type: 'selection'
  },
  {
    field: 'index',
    label: t('tableDemo.index'),
    type: 'index'
  },
  {
    field: 'firstName',
    label: t('tableDemo.firstName')
  },
  {
    field: 'lastName',
    label: t('tableDemo.lastName')
  },

  {
    field: 'email',
    label: '邮箱'
  },
  {
    field: 'phoneNumber',
    label: '手机号'
  },
  {
    field: 'hireDate',
    label: '入职日期',
    formatter: (row) => {
      return row.hireDate ? dayjs(row.hireDate).format('YYYY-MM-DD HH:mm:ss') : '暂无日期'
    }
  },
  {
    field: 'action',
    width: '260px',
    label: t('tableDemo.action'),
    slots: {
      default: (data) => {
        return (
          <>
            <ElButton type="primary" onClick={() => actionFn(data.row)}>
              {t('exampleDemo.edit')}
            </ElButton>
            <ElButton type="success" onClick={() => action(data.row, 'detail')}>
              {t('exampleDemo.detail')}
            </ElButton>
            <ElButton type="danger" onClick={() => delData(data.row)}>
              {t('exampleDemo.del')}
            </ElButton>
          </>
        )
      }
    }
  }
])

const actionFn = (data: TableSlotDefault) => {
  router.push({
    name: 'employeesedit',
    params: {
      id: data.empId
    }
  })
}

const delData = (data: TableSlotDefault) => {
  ElMessageBox.confirm(t('common.delMessage'), t('common.delWarning'), {
    confirmButtonText: t('common.delOk'),
    cancelButtonText: t('common.delCancel'),
    type: 'warning'
  }).then(async () => {
    const res = await delEmployeeApi(data.empId)
    if (res) {
      ElMessage.success('删除成功')
      getList()
    } else {
      ElMessage.error('删除失败')
    }
  })
}

const action = (data: TableSlotDefault, type: string) => {
  router.push({
    name: 'employeesdetail',
    params: {
      id: data.empId
    }
  })
}

const delLoading = ref(false)

const ids = ref<string[]>([])

const batchDel = async () => {
  const elTableExpose = await getElTableExpose()
  ids.value = elTableExpose?.getSelectionRows().map((v) => v.empId) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}

const AddAction = () => {
  router.push({
    name: 'employeesadd'
  })
}

const searchSchemas = reactive<FormSchema[]>([
  {
    field: 'firstName',
    label: t('tableDemo.firstName'),
    component: 'Input',
    colProps: { span: 12 }
  },
  {
    field: 'lastName',
    label: t('tableDemo.lastName'),
    component: 'Input',
    colProps: { span: 12 }
  },
  {
    field: 'email',
    label: '邮箱',
    component: 'Input',
    colProps: { span: 6 }
  },
  {
    field: 'phoneNumber',
    label: '手机号',
    component: 'Select',
    componentProps: {
      options: [
        {
          label: '2345678901',
          value: '2345678901'
        },
        {
          label: '4567890123',
          value: '4567890123'
        },
        {
          label: '0123456789',
          value: '0123456789'
        }
      ]
    },
    colProps: { span: 6 }
  }
])

const searchParams = ref({})
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}
</script>

<template>
  <ContentWrap>
    <Search :schema="searchSchemas" @search="setSearchParams" @reset="setSearchParams" />

    <div class="mb-10px">
      <BaseButton type="primary" @click="AddAction">{{ t('exampleDemo.add') }}</BaseButton>
      <BaseButton :loading="delLoading" type="danger" @click="batchDel()">
        {{ t('exampleDemo.del') }}
      </BaseButton>
    </div>

    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="columns"
      :data="dataList"
      row-key="id"
      :loading="loading"
      sortable
      :pagination="{
        total: total
      }"
      @register="tableRegister"
    />
  </ContentWrap>
</template>
